define(["jquery","echarts","bbcare",
    "scprit/evaluatingPublicPages/vm/gms/gmsDetail.ui.js",
    "scprit/evaluatingPublicPages/vm/gms/gmsDetail.servers.js"],function(jquery,echarts,$bb,$ui,$servers){
    var event = {};
    var saveScoreCallback = function(data,params){
        if(data.success){
            params.result.eva = data.data;
            var inParams = {
                userId:params.userId,
                type:params.type,
                taskId:params.taskId
            };
            $servers.getGmsScore(inParams,event.getGmsScoreCallback,params);
        }else{
            $bb.toastShow(data.msg,1500);
        }
    };
    //运动表现点击事件函数：
    var  performanceClick = function(){
        if(!$(this).hasClass('grey')){
            var color = $(this).css("background-color"),item = $(this).attr("item");
            var info = $(this).data("info");
            var params = {"ps":{}};
            params.type=info.type;
            params.userId = info.userId;
            params.ps.days = info.days;
            params.ps.color = color;
            params.ps.item = item;
            params.ps.posture = $("#posture").val();
            params.ps.birthday = info.birthday;
            params.ps.pregnancDay = info.pregnancyDay;
            $servers.saveScore(params,saveScoreCallback,info);
        }
    };
    //图表：
    //虚拟数据：
    var diotArr = function(){
        var arr = [];
        var min = 185.5,y1 = 6.48,max = 315;
        var num  = 7,i=0,j= 0,k= 1;
        do{
            var y = num*i;
            i++;
            arr.push([(min+y),y1]);
        }while((min+y)<max);

        var min2 = 339.5,y2= 3.48,max2 = 430;
        do{
            var y = num*j;
            j++;
            arr.push([(min2+y),y2]);
        }while((min2+y)<max2);

        var c= 0.5;
        do{
            var y = c*k;
            k++;
            arr.push([325.5,y]);
            arr.push([332.5,y]);
        }while((c+y)<7);
        return arr;
    }
    
    event.charts = function(obj){
        var arr = diotArr();
        var optionsInit = {};
        if(document.body.offsetWidth < 992 ){
            $("#chart").css('width','100%');
            optionsInit = {
                width:520,
                symbolSize:[13,42]
            }
        }else{
            $("#chart").css('width','800px');
            optionsInit = {
                width:750,
                symbolSize:[19.5,42]
            }
        }
        var myChart = echarts.init(document.getElementById('chart'));
        var option = {
            tooltip: {
                trigger: 'item',
                formatter:function(params, ticket, callback){
                    var val='';
                    if(params.seriesType == "scatter" && params.seriesName == "baby"){
                        var name =JSON.parse(params.data.name);
                        var age = "";
                        var getAge = function(days,pregnancDay,birthday){
                            var age ;
                            if(birthday){
                                age = parseInt((days-pregnancDay)/7) + "周" + (days-pregnancDay)%7 + "天";
                            }else{
                                age = parseInt(pregnancDay/7) + "周" + pregnancDay%7 + "天";
                            }
                            return age
                        };
                        age = getAge(name.days*1,name.pregnancDay*1,name.birthday);
                        val += '出生胎龄：'+ age + "<br/>"+'记录体位：'+ name.posture + "<br/>"+'运动表现：'+ name.evaRes + "<br/>"+'评估日期：'+ name.testTime
                    }
                    return val;
                }
            },
            grid: {
                left: '0',
                right: '20',
                bottom: '15',
                top:'10',
                width:optionsInit.width,
                height:'320',
                containLabel: true
            },
            xAxis: {
                type: 'value',
                min:'182',
                max:"434",
                interval:7,
                name:"周",
                nameLocation:"middle",
                nameGap:"24",
                boundaryGap: false,
                axisLabel: {
                    formatter: function(value,index){
                        if(value % 7 == 0){
                            if(value > 280){
                                return parseInt((value-280) / 7)
                            }else{
                                return parseInt(value / 7);
                            }
                        }
                    }
                },
                splitArea : {
                    show : false
                }
            },
            yAxis:  {
                type: 'value',
                name:"",
                nameLocation:"middle",
                nameGap:"27",
                boundaryGap: false,
                min:0,
                max:7,
                interval:1,
                axisLabel: {
                    textStyle: {
                        color: function (value, index) {
                            var color = ["","#AACA57","#70C6C9","#FACE64","#ED9772","#EF7255","#8B549B","#3B6FB3"];
                            return color[value]
                        }
                    },
                    formatter: function(value,index){
                        var label = ["","N","H","PR","Ch","CS","AF","F-"];
                        return label[index]
                    },
                    fontWeight:"bolder",
                    fontSize:"16"
                },
                splitArea : {
                    show : false
                }
            },
            series: [
                {
                    name: 'bg',
                    type: 'scatter',
                    symbol: 'rect',
                    symbolSize: function(value,number){
                        return optionsInit.symbolSize
                    },
                    data:arr,
                    itemStyle: {
                        normal: {
                            color: '#EBEBEB'
                        },
                        emphasis:{
                            color: '#EBEBEB'
                        }
                    },
                    animation:false
                },
                {
                    name:'baby',
                    type:'scatter',
                    symbolSize:"12",
                    data:obj.data
                }
            ]
        };
        myChart.setOption(option);
        $("#printImage").html('<img src="' + myChart.getDataURL({type: "png",backgroundColor: '#fff'}) + '" style="width: 100%;height:100%; "/>');

      /*  myChart.on('click', function (params) {
            console.log(params);
        });*/
    };
    //保存指导建议回调：
    var saveGuidesCallback = function(data,params){
        if(data.success){
            params.result.guide = $.trim($(this).prev("textarea").val()),
            $bb.toastShow("保存成功",1500);
            event.getGuides(params);
        }else{
            $bb.toastShow(data.msg,1500);
        }
    };
    //保存记录的回调函数：
    event.getGmsScoreCallback = function(data,params){
        var result = data.data.result;
        var nowDate = $servers.getNowFormatDate();
        var nowGuides = result[0];
        var history = $servers.curDeal(data.data);
        event.charts({"data":history});
        if(result.length >0){
            $("#body_bottom").html('<span>评估医生：'+ nowGuides.doctorName +'</span>&nbsp;&nbsp;<span>评估日期：'+ $servers.getNowFormatDate() +'</span>');
            $("#eva-info").html('<p class="eva-info">评估医生：'+ nowGuides.doctorName +'</p><p class="eva-info">评估时间：'+ $servers.getNowFormatDate() +'</p>');
            var guides = '';
            if(nowGuides.testTime == nowDate){
                params.result.eva = JSON.parse(nowGuides.result);
                $("#todayGuide").attr("answerId",nowGuides.answerId);
                params.posture = JSON.parse(nowGuides.result).posture;
                var res = $servers.getRes(JSON.parse(nowGuides.result));
                $("#check-res").html('<div class="item">检查结果：</div><div class="item-result">'+res+'</div>');
            }else{
                var h = '<textarea name="guides" class="form-control"></textarea>'+
                    '<button class="btn btn-primary pull-right" id="toSave">保存</button>';
                $("#guides_bottom").html(h);
            }
        }else{
            //打印信息：
            var doctorName =JSON.parse($bb.getSessionStorage("account")).alias;
            $("#body_bottom").html('<span>评估医生：'+ doctorName +'</span>&nbsp;&nbsp;<span>评估日期：'+ $servers.getNowFormatDate() +'</span>');
            $("#eva-info").html('<p class="eva-info">评估医生：'+ doctorName +'</p><p class="eva-info">评估时间：'+ $servers.getNowFormatDate() +'</p>');
            //建议：
            var h = '<textarea name="guides" class="form-control"></textarea>'+
                '<button class="btn btn-primary pull-right" id="toSave">保存</button>';
            $("#guides_bottom").html(h);
        }

    };
    //获取指导意见：
    var getGuidesCallback = function(data,params){
        var guides = data.data.getGuide;
        var nowDate = $servers.getNowFormatDate();
        var nowGuides;
        guides.length = guides.length;
        for(var i = 0;i<guides.length;i++){
            guides[i].testDate = guides[i].createTime.substring(0,10);
            if(nowDate == guides[i].testDate ){
                nowGuides = guides[i];
                params.result.guide = nowGuides.guide;
                $("#todayGuide").attr("guide",nowGuides.guide);
                var h = '<textarea name="guides" class="form-control">'+ nowGuides.guide +'</textarea>'+
                    '<button class="btn btn-primary pull-right" id="toSave">保存</button>';
                $("#guides_bottom").html(h);
            }
        }
        if(!nowGuides){
            $("#check-guide").html('<div class="item">指导建议：</div><div class="item-result"></div>');
            var h = '<textarea name="guides" class="form-control"></textarea>'+
                '<button class="btn btn-primary pull-right" id="toSave">保存</button>';
            $("#guides_bottom").html(h);
        }
        if(params.flag == 1){
            $ui.guideHideListInit({"id":"#hideList","data":guides});
        }else{
            $ui.guideListInit({"id":"#guideList","data":guides,"length":guides.length});
        }

        $(".guides_top span.guide-tab").data("info",params);
        $(".guides_top").on("click","span.guide-label",event.guideListFn);
        $(".guides_top").on("click","span.guide-hide-label",event.guideListFn);
    };
    event.getGuides = function(params){
        $servers.getGuides(params,getGuidesCallback,params);
    };

    event.guideListFn = function(){
        if(!$(this).hasClass('guide-tab')){
            $(".guide-label").removeClass("checked");
            $(this).addClass('checked');
            var guide = $(this).attr("guide") ? $(this).attr("guide"):'' ;
            if($(this).hasClass('todayGuide')){
                var h = '<textarea name="guides" class="form-control">'+ guide +'</textarea>'+
                    '<button class="btn btn-primary pull-right" id="toSave">保存</button>';
            }else{
                h = '<textarea name="guides" class="form-control"  disabled>'+guide+'</textarea>';
            }
            $("#guides_bottom").html(h);
        }
    };
    var guideTabFn = function(){
        if($(this).attr("show")){
            $(".hideList").css("display","none");
            $(this).removeAttr("show");
        }else{
            var info = $(this).data("info");
            $(".hideList").css("display","block");
            $(this).attr("show",true);
            var params = $.extend({},info,{});
            params.flag = 1;
            event.getGuides(params);
        }
    };

    event.init = function(info,result){
        event.getGuides(info);
        $(".generalExercisePerformance").off('click',"span");
        info.result = result;
        $(".generalExercisePerformance span").data("info",info);
        $(".generalExercisePerformance").on('click',"span",performanceClick);

        $(".guides_top").off("click","span.guide-tab");
        $(".guides_top").on("click","span.guide-tab",guideTabFn);
        //保存：
        $(".guides_bottom").on("click","#toSave",function(){
            var inParams = {
                "guide":$.trim($(this).prev("textarea").val()),
                "userId":info.userId,
                "answerId":$("#todayGuide").attr("answerId")
            };
            if(!$("#todayGuide").attr("answerId")){
                $bb.toastShow("今日测评还未做，无法填写指导建议",1500);
                return
            }else{
                if(!$.trim($(this).prev("textarea").val())){
                    $bb.toastConfirmShow(function(){
                        $servers.saveGuides(inParams,saveGuidesCallback,info);
                    },'',"输入内容为空，确定提交？");
                }else{
                    $servers.saveGuides(inParams,saveGuidesCallback,info);
                }
            }
        });

    };
    return event;
});